package com.dzwww.recommend.rule.controller;

import com.dzwww.recommend.rule.common.po.RuleDispose;
import com.dzwww.recommend.rule.controller.vo.RecommendObj;
import com.dzwww.recommend.rule.controller.vo.RecommendView;
import com.dzwww.recommend.rule.service.common.RuleDisposeService;
import com.dzwww.recommend.rule.service.common.ZhiYunImpl;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

/**
 * 推荐api(新版) 
 * 功能：过滤掉要排除的新闻，本案不提供置顶新闻的推荐，置顶的新闻需要查询推荐规则配置API
 * @author Administrator
 * 2019年7月24日
 */
@RestSchema(schemaId = "recommendApiNew")
@RequestMapping(path = "/recommend/api/new", produces = MediaType.APPLICATION_JSON)
@Slf4j
public class RecommendApiNewController  {
	
	@Resource
    RuleDisposeService ruleDisposeService;


	/**
	 * 个性化推荐
	 * @param view
	 * @return
	 */
    @PostMapping("personal")
    public RecommendObj recommend(@RequestBody RecommendView view){
    	log.info("---personal:---" + view.toString());
    	//获取智云推荐的结果
    	String shuWenJson = getShuWenRecommend(view);
    	Gson gson = new Gson();
    	RecommendObj ro = gson.fromJson(shuWenJson, RecommendObj.class);
    	List<String> shuwenList = ro.getData().getNewsIds();
    	//如果智云推荐有数据
    	if(shuwenList.size() > 0){
    		//获取推荐规则配置的过滤新闻ID
        	List<String> ruleList = getRuleList();
        	if(ruleList.size() > 0){
        		//整理推荐列表
        		shuwenList.removeAll(ruleList);
        		if(shuwenList.size() < view.getSize()){
        			recurseRecommend(view, shuwenList, ruleList);
        		}
        	}
    	}
        return ro;
    }
    
    /**
     * 相关新闻推荐
     * @param view
     * @return
     */
    @PostMapping("relative")
    public RecommendObj relative(@RequestBody RecommendView view){
    	log.info("---relative:---" + view.toString());
    	//获取智云推荐的结果
    	String shuWenJson = getShuWenRelative(view);
    	Gson gson = new Gson();
    	RecommendObj ro = gson.fromJson(shuWenJson, RecommendObj.class);
    	List<String> shuwenList = ro.getData().getNewsIds();
    	//如果智云推荐有数据
    	if(shuwenList.size() > 0){
    		//获取推荐规则配置的过滤新闻ID
        	List<String> ruleList = getRuleList();
        	if(ruleList.size() > 0){
        		//整理推荐列表
        		shuwenList.removeAll(ruleList);
        	}
    	}
    	return ro;
    }
    
    /**
     * 热点新闻推荐
     * @param view
     * @return
     */
    @PostMapping("hot")
    public RecommendObj hot(@RequestBody RecommendView view){
    	log.info("---hot:---" + view.toString());
    	//获取智云推荐的结果
    	String shuWenJson = getShuWenHot(view);
    	Gson gson = new Gson();
    	RecommendObj ro = gson.fromJson(shuWenJson, RecommendObj.class);
    	List<String> shuwenList = ro.getData().getNewsIds();
    	//如果智云推荐有数据
    	if(shuwenList.size() > 0){
    		//获取推荐规则配置的过滤新闻ID
        	List<String> ruleList = getRuleList();
        	if(ruleList.size() > 0){
        		//整理推荐列表
        		shuwenList.removeAll(ruleList);
        		if(shuwenList.size() < view.getSize()){
        			recurseHot(view, shuwenList, ruleList);
        		}
        	}
    	}
    	return ro;
    }
    
    private String getShuWenRecommend(RecommendView view){
    	return ZhiYunImpl.recommend(view);
    }
    
    private String getShuWenRelative(RecommendView view){
    	return ZhiYunImpl.relative(view);
    }
    
    private String getShuWenHot(RecommendView view){
    	return ZhiYunImpl.hot(view);
    }
    
    private List<String> getRuleList(){
    	List<String> ruleList = new ArrayList<String>();
    	RuleDispose ruleDispose = new RuleDispose();
    	ruleDispose.setType(2);
    	ruleDispose.setStatus(1);
    	List<RuleDispose> list = ruleDisposeService.listBy(ruleDispose);
    	if(list != null && list.size() > 0){
    		Iterator<RuleDispose> it = list.iterator();
            while(it.hasNext()){
            	RuleDispose rd = (RuleDispose)it.next();
                if(rd.getValidDays() != null){
    				Calendar nowDate = Calendar.getInstance();
    				Calendar end = Calendar.getInstance();
    				end.setTime(rd.getEffectiveEndtime());
    				if(nowDate.after(end)) {
    					it.remove();
    				}
    			}
            }
            log.info("---过滤规则有:" + list.size() + "条");
    	}
    	//组合所有的newsId
    	if(list != null && list.size() > 0){
    		Set<String> set = new HashSet<String>();
    		for(RuleDispose rd : list){
    			String[] str = rd.getIds().split(",");
    			for(String s : str){
    				set.add(s.trim());
    			}
    		}
    		ruleList = new ArrayList<String>(set);
    	}
    	return ruleList;
    }
    
    private void recurseRecommend(RecommendView view, List<String> shuwenList, List<String> ruleList){
    	//再从智云推荐拉取数据
    	String result = getShuWenRecommend(view);
    	Gson gson = new Gson();
    	RecommendObj ro = gson.fromJson(result, RecommendObj.class);
    	List<String> continueList = ro.getData().getNewsIds();
		if(continueList == null || continueList.size() == 0){
			log.info("---recurseRecommend：智云的个性化推荐没有数据---");
			return;
		}
		continueList.removeAll(ruleList);
		int num = shuwenList.size() + continueList.size();
		if(num == view.getSize()){
			shuwenList.addAll(continueList);
		}
		if(num < view.getSize()){
			//递归
			shuwenList.addAll(continueList);
			recurseRecommend(view, shuwenList, ruleList);
		}
		if(num > view.getSize()){
			int sub = view.getSize() - shuwenList.size();
			continueList = continueList.subList(0, sub);
			shuwenList.addAll(continueList);
		}
    }
    
    private void recurseHot(RecommendView view, List<String> shuwenList, List<String> ruleList){
    	//再从智云推荐拉取数据
    	String result = getShuWenHot(view);
    	Gson gson = new Gson();
    	RecommendObj ro = gson.fromJson(result, RecommendObj.class);
    	List<String> continueList = ro.getData().getNewsIds();
		if(continueList == null || continueList.size() == 0){
			log.info("---recurseHot：智云的热点新闻推荐没有数据---");
			return;
		}
		continueList.removeAll(ruleList);
		int num = shuwenList.size() + continueList.size();
		if(num == view.getSize()){
			shuwenList.addAll(continueList);
		}
		if(num < view.getSize()){
			//递归
			shuwenList.addAll(continueList);
			recurseHot(view, shuwenList, ruleList);
		}
		if(num > view.getSize()){
			int sub = view.getSize() - shuwenList.size();
			continueList = continueList.subList(0, sub);
			shuwenList.addAll(continueList);
		}
    }
    
}